package com.example.myapplication.fraction;

import com.example.baselib.base.BaseFraction;
import com.example.baselib.utils.TextUtils;
import com.example.baselib.utils.ToastUtils;
import com.example.baselib.utils.UIUtils;
import com.example.baselib.utils.log.LogUtils;
import com.example.baselib.widget.BGGImage;
import com.example.myapplication.BuildConfig;
import com.example.myapplication.ResourceTable;
import com.example.myapplication.data.EConstants;
import com.example.myapplication.data.People;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.utils.Rect;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;

import java.util.ArrayList;
import java.util.List;

public class MainFraction extends BaseFraction {

    private AbilitySlice mAbilitySlice;
    private PageSlider pageSlider;
    private PageSliderProvider sliderProvider;
    private PageSliderIndicator pageSliderIndicator;
    private List<BGGImage> componentsList;
    private ListContainer listContainer;
    private MyProvider itemProvider;
    private int clickIndex;
    List<People> peoples = new ArrayList<>();

    EventHandler handler = new EventHandler(EventRunner.getMainEventRunner());

    public MainFraction(AbilitySlice abilitySlice) {
        this.mAbilitySlice = abilitySlice;
    }

    @Override
    protected int getComponentUIResId() {
        return ResourceTable.Layout_fraction_main;
    }

    @Override
    protected void initComponent() {
        listContainer = UIUtils.findComponentFromId(mRootComponent, ResourceTable.Id_list_container);
        pageSlider = UIUtils.findComponentFromId(mRootComponent, ResourceTable.Id_page_slider);
        pageSliderIndicator = UIUtils.findComponentFromId(mRootComponent, ResourceTable.Id_page_slider_indicator);

        //设置圆点样式
        Rect rect = new Rect(0, 0, UIUtils.vp2px(mContext, 10), UIUtils.vp2px(mContext, 10));
        ShapeElement normal = new ShapeElement();
        normal.setRgbColor(new RgbColor(255, 255, 255, 99));
        normal.setShape(ShapeElement.OVAL);
        normal.setBounds(rect);
        ShapeElement select = new ShapeElement();
        select.setRgbColor(new RgbColor(255, 0, 0));
        select.setShape(ShapeElement.OVAL);
        select.setBounds(rect);

        pageSliderIndicator.setItemElement(normal, select);
        //设置适配器
        pageSlider.setProvider(sliderProvider = new PageSliderProvider() {
            @Override
            public int getCount() {
                return componentsList == null ? 0 : componentsList.size();
            }

            @Override
            public Object createPageInContainer(ComponentContainer componentContainer, int i) {
                Component component = componentsList.get(i);
                componentContainer.addComponent(component);
                return componentContainer;
            }

            @Override
            public void destroyPageFromContainer(ComponentContainer componentContainer, int i, Object o) {
                BGGImage image = componentsList.get(i);
                componentContainer.removeComponent(image);
            }

            @Override
            public boolean isPageMatchToObject(Component component, Object o) {
                return component == o;
            }
        });
        pageSliderIndicator.setPageSlider(pageSlider);

    }

    @Override
    protected void initData() {
        super.initData();
        String[] imgs = {
                "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fattach.bbs.miui.com%2Fforum%2F201311%2F01%2F215828tpmddz2d2bfcz5pk.jpg&refer=http%3A%2F%2Fattach.bbs.miui.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620523369&t=12d97859869c3706d873debba8044ed9",
                "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.2008php.com%2F2016_Website_appreciate%2F2016-07-15%2F20160715221151.jpg&refer=http%3A%2F%2Fwww.2008php.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620523414&t=64b0f644af6b2dd3b375bca3709d28cb",
                "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fgss0.baidu.com%2F-4o3dSag_xI4khGko9WTAnF6hhy%2Fzhidao%2Fpic%2Fitem%2F0eb30f2442a7d9330c27cc77a54bd11373f00122.jpg&refer=http%3A%2F%2Fgss0.baidu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620523548&t=41b8141618cff4ae1f048df7e4558652",
                "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg9.51tietu.net%2Fpic%2F2019-091304%2Fqykcbtrrmndqykcbtrrmnd.jpg&refer=http%3A%2F%2Fimg9.51tietu.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620523470&t=b1d1399e0f04b89bbba5d5023911a33a"
        };
        BGGImage bggImage;
        componentsList = new ArrayList<>();
        for (int i = 0; i < imgs.length; i++) {
            bggImage = new BGGImage(mContext);
            bggImage.load(imgs[i]);
            componentsList.add(bggImage);
        }
        sliderProvider.notifyDataChanged();
        //定时滚动
        handler.postTask(runnable, 3000);

        //添加测试数据
        People people;
        for (int i = 1; i <= 10; i++) {
            people = new People();
            people.name = "张 " + i;
            people.avatar = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic1.zhimg.com%2F50%2Fv2-e73ebe5fb7fbae39d69ed94dcc82f145_hd.jpg&refer=http%3A%2F%2Fpic1.zhimg.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1620541089&t=f3a8ed22e527f9022ce9a91acbed4ddd";
            peoples.add(people);
        }

        itemProvider = new MyProvider(peoples);
        listContainer.setItemProvider(itemProvider);
        //添加点击事件
        itemProvider.addClickListener((component, index) -> {
            switch (component.getId()) {
                case ResourceTable.Id_img_avatar:
                    clickIndex = index;
                    //开启摄像头拍照
                    if (mAbilitySlice != null) {
                        Intent mIntent = new Intent();
                        mIntent.setOperation(new Intent.OperationBuilder()
                                .withBundleName(BuildConfig.PACKAGE_NAME)
                                .withAction(EConstants.Action.ACTION_AVATAR)
                                .build());
                        mAbilitySlice.startAbilityForResult(mIntent, EConstants.REQUEST_CODE_CAMERA);
                    }
                    break;
                default:
                    ToastUtils.show(mContext, "当前点击: " + (index + 1));
            }
        }, ResourceTable.Id_img_avatar);
    }


    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            int index = pageSliderIndicator.getSelected();
            int count = pageSliderIndicator.getCount();
            int curr = (index + 1) % count;
            pageSliderIndicator.setSelected(curr);
            handler.postTask(runnable, 3000);
        }
    };


    class MyProvider extends BaseItemProvider {

        private List<People> mList;
        private OnClickListener mListener;
        private int[] mCId;

        MyProvider(List<People> peopleList) {
            this.mList = peopleList;
        }

        public void addClickListener(OnClickListener listener, int... cId) {
            this.mListener = listener;
            this.mCId = cId;
        }

        @Override
        public int getCount() {
            return mList == null ? 0 : mList.size();
        }

        @Override
        public Object getItem(int i) {
            return mList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
            Component layout;
            if (component == null) {
                layout = LayoutScatter.getInstance(mContext).parse(ResourceTable.Layout_item_main_fraction, null, false);
            } else {
                layout = component;
            }

            People item = (People) getItem(i);

            Text text = UIUtils.findComponentFromId(layout, ResourceTable.Id_tt_name);
            BGGImage avatar = UIUtils.findComponentFromId(layout, ResourceTable.Id_img_avatar);
            text.setText(item.name);
            avatar.load(item.avatar);
            avatar.setCornerRadius(avatar.getWidth() / 2f);
            if (mListener != null && mCId != null && mCId.length > 0) {
                for (int id : mCId) {
                    UIUtils.findComponentFromId(layout, id)
                            .setClickedListener(component12 -> mListener.onClickComponent(component12, i));
                }
            }
            layout.setClickedListener((component1) -> {
                if (mListener != null) {
                    mListener.onClickComponent(component1, i);
                }
            });

            return layout;
        }
    }

    @Override
    public boolean onAbilityResultIntercept(int requestCode, int resultCode, Intent resultData) {
        if (requestCode == EConstants.REQUEST_CODE_CAMERA) {
            try {
                String test = resultData.getStringParam("test");
                LogUtils.i("获取测试数据:%s", test);
                People people = peoples.get(clickIndex);
                people.avatar = test;
                //数据刷新
                itemProvider.notifyDataChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }


            return true;
        }
        return super.onAbilityResultIntercept(requestCode, resultCode, resultData);
    }

    interface OnClickListener {
        void onClickComponent(Component component, int index);
    }

}
